package com.super8.super8newtv;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.reflect.TypeToken;
import com.super8.super8newtv.api.Api;
import com.super8.super8newtv.api.ApiContract;
import com.super8.super8newtv.api.ApiError;
import com.super8.super8newtv.api.ApiService;
import com.super8.super8newtv.api.parser.TokenBeanParser;
import com.super8.super8newtv.bean.ResponseBean;
import com.super8.super8newtv.bean.TokenBean;
import com.super8.super8newtv.utils.CacheUtil;
import com.super8.super8newtv.utils.LogUtils;
import com.super8.super8newtv.utils.Utils;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends Activity {

    @BindView(R.id.et_login_code)
    EditText etLoginCode;//登录码
    @BindView(R.id.et_login_password)
    EditText etLoginPassword;//登录密码
    @BindView(R.id.tv_login_super8Price)
    TextView tvLoginSuper8Price;//登录按钮
    @BindViews({R.id.rb_screen_across, R.id.rb_screen_clockwise, R.id.rb_screen_anticlockwise})
    List<RadioButton> lsRadio;//横屏，顺时针，逆时针

    private SharedPreferences config;
    private SharedPreferences.Editor edit;

    private String client_id, client_secret = "123456";//机器id,机器秘钥

    static class HomeHandler extends Handler {
        private final WeakReference<MainActivity> homeFragmentWeakReference;

        HomeHandler(MainActivity mainActivity) {
            homeFragmentWeakReference = new WeakReference<MainActivity>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final MainActivity activity = homeFragmentWeakReference.get();
            if (activity == null || activity.isFinishing()) {
                removeCallbacksAndMessages(null);
                return;
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private MainActivity.HomeHandler mHandler = new MainActivity.HomeHandler(MainActivity.this) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:  //登录失败提示
                    String showMsg = msg.getData().getString("msg");
                    showToast(showMsg);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        CacheUtil.getCache(this).put("screenType", "Horizontal");//默认竖屏
        initView();
        initData();
    }

    /**
     * 业务描述:登录
     *
     * @param :
     * @return
     * @创 建 人: zhangl
     * @创建时间:2020-07-08 09:44:25
     */
    @OnClick({R.id.tv_login_super8Price, R.id.rb_screen_across, R.id.rb_screen_anticlockwise, R.id.rb_screen_clockwise})
    public void onClickListener(View v) {
        switch (v.getId()) {
            case R.id.tv_login_super8Price:
                if (!lsRadio.get(2).isChecked())
                    if (!TextUtils.isEmpty(etLoginCode.getText().toString()) && !TextUtils.isEmpty(etLoginPassword.getText().toString()))
                        getToken();
                    else
                        showToast("机器代码或密码不能为空!");
                else {
                    client_id = etLoginCode.getText().toString();
                    startActivity(initScreenTypeView());
                }
                break;
            case R.id.rb_screen_across://横屏
                CacheUtil.getCache(this).put("screenType", "Horizontal");
                break;
            case R.id.rb_screen_clockwise://顺时针
                CacheUtil.getCache(this).put("screenType", "clockwise");
                break;
            case R.id.rb_screen_anticlockwise://逆时针
                CacheUtil.getCache(this).put("screenType", "anti_clockwise");
                break;
        }
    }

    private void initView() {
        initScreenTypeView();//显示
    }

    private void initData() {
        config = getSharedPreferences("token", MODE_MULTI_PROCESS);
        edit = config.edit();

        //判断是否记住账户，密码
        String id = CacheUtil.getCache(MainActivity.this).getString("client_id", "");
        String secret = CacheUtil.getCache(MainActivity.this).getString("client_secret", "");
        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(secret)) {
            etLoginCode.setText(id);
            etLoginPassword.setText(secret);
            getToken();//获取token 登录
        } else if (!TextUtils.isEmpty(id)) {
            etLoginCode.setText(id);
        }
    }

    //初始显示类型屏幕
    private Intent initScreenTypeView() {
        Intent anticIntent = new Intent(MainActivity.this, DetailsActivity.class);
        anticIntent.putExtra("hotelId", 000066);
        String screenType = CacheUtil.getCache(this).getString("screenType", "Horizontal");
        LogUtils.e("getVideoList", "====anti_clockwise================ssssss======================");
        switch (screenType) {
            case "Horizontal":  //横版
                anticIntent = new Intent(MainActivity.this, HorizontalActivity.class);
                lsRadio.get(0).setChecked(true);
                break;
            case "across":  //横版
                lsRadio.get(0).setChecked(true);
                anticIntent.putExtra("direction", "across");
                break;
            case "clockwise":  //顺时针竖版
                lsRadio.get(1).setChecked(true);
                anticIntent = new Intent(MainActivity.this, ClockwiseActivity.class);
                anticIntent.putExtra("direction", "clockwise");
                break;
            case "anti_clockwise":  //逆时针竖版
                lsRadio.get(2).setChecked(true);
//                anticIntent = new Intent(MainActivity.this, TVActivity.class);
//                anticIntent.putExtra("direction", "anticlockwise");
//                anticIntent.putExtra("url", client_id);
                LogUtils.e("getVideoList", "====anti_clockwise");
                anticIntent = new Intent(MainActivity.this, TVHomeActivity.class);
                break;
        }
        return anticIntent;
    }

    /**
     * 获取token
     */
    private void getToken() {
        client_id = etLoginCode.getText().toString();
        client_secret = etLoginPassword.getText().toString();
        String versionName = Utils.getVersionName(MainActivity.this);
        String deviceId = Utils.getDeviceId(MainActivity.this);
        String currentapiVersion = "android_" + Build.VERSION.RELEASE;
        HashMap<String, String> reqMap = new HashMap<>();
        reqMap.put("device_id", deviceId);
        reqMap.put("os_version", currentapiVersion);
        reqMap.put("version", versionName);
        reqMap.put("grant_type", "client_credentials");
        reqMap.put("client_id", client_id);
        reqMap.put("client_secret", client_secret);
        reqMap.put("screentype", CacheUtil.getCache(this).getString("screenType", "across").equals("across") ? "H" : "V");

        TokenBeanParser<TokenBean> responseBeanParser = new TokenBeanParser<TokenBean>(new TypeToken<TokenBean>() {
        }.getType());
        ApiService.getInstance().get(Api.ACCESS_TOKEN, reqMap, responseBeanParser, new ApiContract.OnResponseListener<TokenBean>() {

            @Override
            public void onSuccess(ResponseBean<TokenBean> result) {
                if (result.isSuccess()) {//登录成功
                    CacheUtil.setTokenCache(MainActivity.this, result.getData());//保存token
                    CacheUtil.getCache(MainActivity.this).put("client_id", client_id);
                    CacheUtil.getCache(MainActivity.this).put("client_secret", client_secret);
                    startActivity(initScreenTypeView());
                } else {
//                    CacheUtil.getCache(MainActivity.this).remove("client_id");
//                    CacheUtil.getCache(MainActivity.this).remove("client_secret");
                    //发送数据
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", "登录失败!机器代码或密码有误！" + result.getError_description());
                    Message message = Message.obtain();
                    message.setData(bundle);   //message.obj=bundle  传值也行
                    message.what = 1;
                    mHandler.sendMessage(message);
                }
            }

            @Override   //登录失败
            public void onError(ApiError error) {
//                CacheUtil.getCache(MainActivity.this).remove("client_id");
//                CacheUtil.getCache(MainActivity.this).remove("client_secret");
                LogUtils.e("getToken ", "onError:" + error.getErrorMessage());
                //发送数据
                Bundle bundle = new Bundle();
                bundle.putString("msg", "登录异常!" + error.getErrorMessage());
                Message message = Message.obtain();
                message.setData(bundle);   //message.obj=bundle  传值也行
                message.what = 1;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScreenTypeView();
    }

    //提示信息
    private void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
